# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Random seed
np.random.seed(123)

# NUMBER OF ASSETS
n_assets = 4

# NUMBER OF OBSERVATIONS
n_obs = 1000

return_vec = np.random.randn(n_assets, n_obs)
# print(return_vec.shape) # n_assets个标的（行），n_obs次观测值（列）




exit()
plt.plot(return_vec.T, alpha=.4)
plt.xlabel('time')
plt.ylabel('returns')
# plt.savefig('random_ret.jpg')



# 生成随机权重
def rand_weights(n):
    ''' Produces n random weights that sum to 1 '''
    k = np.random.rand(n)
    return k / sum(k)


# 生成随机组合
def random_portfolio(returns):
    ''' 
    Returns the mean and standard deviation of returns for a random portfolio
    '''
    # 每日收益率序列是根据“已知（或估计）的正态ret随机变量生成的”
    p = np.asmatrix(np.mean(returns, axis=1))
    # 随机生成各资产权重
    w = np.asmatrix(rand_weights(returns.shape[0]))
    C = np.asmatrix(np.cov(returns))

    mu = w * p.T
    sigma = np.sqrt(w * C * w.T)

    # This recursion reduces outliers to keep plots pretty
    # 后期要作图，希望让 风险-收益 的点，出现在一个适合显示的范围
    # （因为不限制的话，这些点可能会飞到很远的地方去）
    if sigma > 1:  # （如果std>1，后面就不显示这个点）
        return random_portfolio(returns)  # 重新计算
    return mu, sigma



# 这里仿真n_portfolios个资产组合
n_portfolios = 1000
means, stds = np.column_stack(
    [random_portfolio(return_vec) for _ in range(n_portfolios)])



plt.plot(stds, means, 'o', markersize=5)
plt.xlabel('std')
plt.ylabel('mean')
plt.title(
    'Mean and standard deviation of returns of randomly generated portfolios')

# plt.savefig('risk_ret.jpg')
plt.show()